from abc import ABC

from services.base.biz_service import BizService


class BaseCommonService(BizService, ABC):
    def __init__(self, model_class, time_field=None):
        super().__init__(model_class)
        self.model_class = model_class
        self.time_field = time_field

    def get_total_count(self, start_time, end_time, session=None):
        # 如果未提供session，则获取新的session
        if session is None:
            session = self.get_session()

        count = session.query(self.model_class).filter(
            getattr(self.model_class, self.time_field).between(start_time, end_time)
        ).count()

        return count

    def get_items(self, start_time, end_time, page_num=0, page_size=1000, session=None):
        # 如果未提供session，则获取新的session
        if session is None:
            session = self.get_session()

        items = session.query(self.model_class).filter(
            getattr(self.model_class, self.time_field).between(start_time, end_time)
        ).offset(page_num * page_size).limit(page_size).all()

        return items

    def get_table_fields(self, exclude_fields=None) -> [str]:
        """
        获取表中字段的 list 集合
        :param exclude_fields: 需要排除的字段
        :return: []
        """
        if exclude_fields is not None:
            return [col for col in self.model_class.__table__.columns.keys() if col not in exclude_fields]
        return self.model_class.__table__.columns.keys()
